package com.fingard.avatar.website.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fingard.avatar.website.dao.SysUserTokenMapper;
import com.fingard.avatar.website.model.po.SysUserTokenPo;
import com.fingard.avatar.website.service.SysUserTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 *  Service实现类
 *
 * @author 徐一涛
 * @date 2022-04-26
 */
@Slf4j
@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserTokenPo> implements SysUserTokenService {

    @Override
    public void add(String token, Long userId) {
        SysUserTokenPo userToken = new SysUserTokenPo().setToken(token).setUserId(userId).
                setCreateTime(LocalDateTime.now());
        save(userToken);
    }

    @Override
    public Long getValidToken(String token) {
        LocalDate date = LocalDate.now().plusDays(-1);
        SysUserTokenPo userToken = getOne(Wrappers.<SysUserTokenPo>lambdaQuery().
                eq(SysUserTokenPo::getToken, token).
                gt(SysUserTokenPo::getCreateTime, date));

        return Optional.ofNullable(userToken).map(SysUserTokenPo::getUserId).orElse(null);
    }
}